package com.geqian.web.file;

import org.apache.commons.io.monitor.FileAlterationListener;
import org.apache.commons.io.monitor.FileAlterationMonitor;
import org.apache.commons.io.monitor.FileAlterationObserver;

import java.io.File;

public class FileMonitor {

    private final FileAlterationMonitor monitor;

    /**
     *
     * @param interval 监听间隔时间，单位毫秒
     */
    public FileMonitor(long interval) {
        monitor = new FileAlterationMonitor(interval);
    }

    /**
     * 监听
     *
     * @param filePath 文件路径
     * @param listener 文件监听器
     */
    public void addFileListener(String filePath, FileAlterationListener listener) {
        addFileListener(new File(filePath), listener);
    }


    /**
     * 给文件添加监听
     *
     * @param file     文件
     * @param listener 文件监听器
     */
    public void addFileListener(File file, FileAlterationListener listener) {
        file = file.isFile() ? file.getParentFile() : file;
        FileAlterationObserver observer = new FileAlterationObserver(file);
        monitor.addObserver(observer);
        observer.addListener(listener);
    }


    public void stop() throws Exception {
        monitor.stop();
    }


    public void start() {
        try {
            System.out.println("------------文件监控中-----------------");
            monitor.start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}